* This local, `1', inputs `nn' from the do file that called this worker file (see `nn' following the do command)
local nn = `1'
rename lprod_`nn' lA

sort pid
*Groups
egen JT		=group(J T)
egen ST		=group(S T)
egen SJT	=group(S J T)

*Tau weights
bys SJT : egen emp_SJT	= total(empl)
bys ST	: egen emp_ST	= total(empl)
gen empshare_SJT 		= emp_SJT/emp_ST

egen tag_SJT	= tag(SJT)
egen tag_ST		= tag(ST)

*Generate FEs from microdata
*taus
quietly reghdfe lA [aw=empl], absorb(temp_tau=SJT) keepsingletons
quietly reghdfe temp_tau  if tag_SJT, absorb(JT) resid keepsingletons
predict tau if e(sample), resid	
			
*xi
quietly reghdfe tau [aw=empshare_SJT], absorb(xi_temp=ST)  keepsingletons
quietly reghdfe xi_temp if tag_ST, absorb(T) resid keepsingletons
predict xi if e(sample), resid

*collapse data to cell level (or city level), recenter, and assess variances

quietly tabstat xi if tag_ST, stat(N var mean) save
matrix stats	=r(StatTotal)
gen N_xi		=stats[1,1]
gen var_xi	=stats[2,1]

quietly tabstat tau [aw=empshare_SJT] if tag_SJT, stat(N var mean) save
matrix stats	=r(StatTotal)
gen N_tau		=stats[1,1]
gen var_tau		=stats[2,1]

keep if tag_SJT
keep var*  tau  xi   S T J N_*
ren (var*  tau  xi  N_* ) =_`nn'
